package cn.tedu.v1.v3;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * 聊天室 Version    1
 * 功能:  1.客户端--指定TP，端口号大
 *       2.客户端给服务器发送文本
 *       3.客户端完成标准I0
 * 【新增】4.捕获异常:打印异常信息--异常全部抓住，用户明确提示
 *        5，关闭socket
 */
public class Client {
    private Socket socket;
    //1.私有化IP
    private String ip;
    public Client(){
        try {
            socket=new Socket("192.168.62.151",0101);
            //2.确定传入IP就是当前IP地址
            ip=socket.getInetAddress().getHostAddress();
        } catch (SocketException e){
            System.out.println("连接被重置或者断开");
        } catch (UnknownHostException e){
            System.out.println("IP地址有问题，请询问服务器端！");
        } catch (IOException e) {
            System.out.println("客户端主动退出了：断开连接");
        }
    }
    //1.start方法:I0流操作:写出功能，实现读入功能交给线程处理
    public void start() {
     PrintWriter pw = null;
    //1,6置空流-赋值、关
        try {
        //1.2读入操作
        InputStream is = socket.getInputStream();
        InputStreamReader isr =
                new InputStreamReader(is, "UTF8");
        BufferedReader br = new BufferedReader(isr);

        //1.1 写出操作
        pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);

        //1,3创建线程--Lambda--读入功能--存线程中
        new Thread(() -> {
            try {
                //1,4线程中--创建变量--接收服务器端发来的文本
                String message;
                //1,5 一直接收客户端发来的消息：message只要与数据一直输出
                while ((message = br.readLine()) != null) {
                    System.out.println("服务器说：" + message);
                    //1,6增加一句话--每次客户端发给服务器内
                    System.out.println("客户端请输入：");
                }
            } catch (IOException e) {
                System.out.println("客户端发来的消息断开了~");
            }
        }).start();

        System.out.println(ip + "客户端用户：请输入文字：");
        Scanner input = new Scanner(System.in);
        while (true) {
            String say = input.nextLine();
            pw.println("客户端说" + say);

        }

    } catch (UnsupportedEncodingException e){
        System.out.println("客户端与服务器端：字符集不一致！");
    } catch (IOException e) {
        System.out.println("客户端断开了连接！");
    } finally {
        //关闭流  关闭socket
        if (pw!=null)
            pw.close();
        if (socket!=null&&!socket.isClosed()){
            System.out.println(ip+"服务端关闭成功！success~");
            try {
                socket.close();
            } catch (IOException e) {
                System.out.println(ip+"客户端关闭失败");
            }
        }
    }

    }

    public static void main(String[] args){
        Client client=new Client();
        client.start();
    }
}